//
//  HomeOwnViewModel.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/2/3.
//

import Foundation
import LeanCloud
//Vip
class VipViewModel : BaseViewModel {
    @Published var items = [VipConfigBean]()
    @Published var selectedIndex: Int = 0
    @Published var status = ""
    
    func getData(_ isRefresh: Bool = false) {
        requestList(isRefresh: isRefresh) {
            let query = LCQuery(className: "VipConfig22")
            query.whereKey("type", .equalTo(0))
            query.whereKey("hide", .equalTo(false))
            query.whereKey("sort", .ascending) //升序
            let list =  try await LeancloudManager.instance.getList(query: query, modeType: VipConfigBean.self)
            try check(!isRefresh || !list.isEmpty, "暂无数据")
            return list
        } suc: { diarys in
            self.status = ""
            self.items.append(contentsOf: diarys)
        } fail: {
            self.status = $0.message
        }
    }
    
    func getProductId() -> String {
        return items[selectedIndex].productId ?? ""
    }
    
    func getPay() {
        let bean = items[selectedIndex]
        //获取购买方式，并且提交预览数据，用于后台查看
        request(isLoading: false) {
            //预览数据
            try await retry(maxRetries: 5, retryDelayMillis: 200) {
                var record = VipPrePayRecordBean()
                record.userId = userManager.getUserId()
                record.userName = userManager.getName()
                record.channel = "apple"
                record.json = toJson(bean)
                try await LeancloudManager.instance.save(todo: record)
            }
            return ""
        } suc: { _ in
            
        } fail: {_ in
        }
    }
    
    func doBuy(productID: String) {
        request {
            let query = LCQuery(className: "VipConfig22")
            query.whereKey("productId", .equalTo(productID))
            let bean =  try await LeancloudManager.instance.getFirst(query: query, modeType: VipConfigBean.self)
            try check(bean != nil, "未找到有效的产品 ID")
            let netTime = try await getNetTime()
            let curTime = getMillisecond(netTime)
            let userBean = userManager.user
            try check(userBean != nil, "用户信息获取失败")
            userBean!.vipSource = Int(bean?.vipSource ?? 0)
            if (bean?.day ?? 0 > 0) {
                userBean!.vipExpiration = curTime + Int64(1000 * 60 * 60 * 24) *  Int64((bean?.day ?? 0))
            } else {
                userBean!.vipExpiration = -1
            }
            if (bean?.aiChatCount ?? 0 < 0) {
                //无限
                userBean!.aiChatCount = bean?.aiChatCount ?? 0
            } else {
                userBean!.aiChatCount += bean?.aiChatCount ?? 0
                
            }
            //复刻音色
            let aiVoiceClone = userBean!.getExtraConfig().aiVoiceClone ?? 0
            userBean!.getExtraConfig().aiVoiceClone = aiVoiceClone + (bean?.aiVoiceCount ?? 0)
            //音色制作
            let aiVoiceCreate = userBean!.getExtraConfig().aiVoiceCreate ?? 0
            userBean!.getExtraConfig().aiVoiceCreate = aiVoiceCreate + (bean?.aiVoiceCreate ?? 0)
            //图标
            let customIconCount = userBean!.getExtraConfig().customIconCount ?? 0
            userBean!.getExtraConfig().customIconCount = customIconCount + (bean?.customIconCount ?? 0)
            //气泡
            let bubbleCount = userBean!.getExtraConfig().bubbleCount ?? 0
            userBean!.getExtraConfig().bubbleCount = bubbleCount + (bean?.bubbleCount ?? 0)
            try await retry(maxRetries: 15, retryDelayMillis: 200) {
                try await LeancloudManager.instance.save(todo: userBean!)
                userManager.saveUser(userBean)
            }
            //邀请奖励
            try await InviteRewardUtils.doUpdatePro(userManager.getUser()?.inviteUserId, bean?.title ?? "", bean?.inviteCount ?? 0)
            //购买记录
            try await retry(maxRetries: 5, retryDelayMillis: 200) {
                var record = VipPayRecordBean()
                record.userId = userManager.getUserId()
                record.userName = userManager.getName()
                record.channel = "apple"
                record.payType = "苹果"
                record.bean = bean
                try await LeancloudManager.instance.save(todo: record)
            }
            //云相册
            return bean
        } suc: { (bean : VipConfigBean?) in
            showToast("升级成功")
            userManager.requestReceiveCloud(capacityType: bean?.capacityType ?? 0)
        } fail: {_ in
        }
    }
    
}
